from datetime import datetime
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import os
import urllib.parse
import requests

class RequestHandler(BaseHTTPRequestHandler):
    # 设置存储PDF的目录
    PDF_UPLOAD_DIR = "uploaded_pdfs"
    json_obj = {}

    def __init__(self, *args, **kwargs):
        # 确保上传目录存在
        if not os.path.exists(self.PDF_UPLOAD_DIR):
            os.makedirs(self.PDF_UPLOAD_DIR)
        super().__init__(*args, **kwargs)

    def generate_timestamp_filename(self, original_filename):
        """生成带时间戳的文件名"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        return f"{timestamp}_{original_filename}"

    def parse_multipart(self, content, boundary):
        """解析multipart/form-data内容"""
        parts = content.split(b'--' + boundary.encode())
        result = {}

        for part in parts:
            if b'Content-Disposition: form-data;' not in part:
                continue

            # 获取字段名
            name_start = part.find(b'name="') + 6
            name_end = part.find(b'"', name_start)
            field_name = part[name_start:name_end].decode('utf-8')

            # 处理文件字段
            if b'filename="' in part:
                # 提取文件名
                filename_start = part.find(b'filename="') + 10
                filename_end = part.find(b'"', filename_start)
                filename = part[filename_start:filename_end].decode('utf-8')

                # 提取文件内容
                file_content_start = part.find(b'\r\n\r\n') + 4
                file_content_end = part.rfind(b'\r\n')
                file_content = part[file_content_start:file_content_end]

                result[field_name] = {
                    'filename': filename,
                    'content': file_content,
                    'is_file': True
                }
            else:
                # 处理普通字段
                value_start = part.find(b'\r\n\r\n') + 4
                value_end = part.rfind(b'\r\n')
                field_value = part[value_start:value_end].decode('utf-8')
                result[field_name] = {
                    'value': field_value,
                    'is_file': False
                }

        return result

    def do_POST(self):
        # 只处理特定路径的请求
        if self.path != "/elkhisagent/report/upload":
            self.send_response(404)
            self.end_headers()
            return

        try:
            content_type = self.headers.get('Content-Type', '')

            # 处理纯JSON数据 (application/json)
            if 'application/json' in content_type:
                content_length = int(self.headers.get('Content-Length', 0))
                post_data = self.rfile.read(content_length)

                # 解码JSON数据，确保正确处理中文
                json_data = json.loads(post_data.decode('utf-8'))
                print("\nReceived JSON data:")
                print(json.dumps(json_data, ensure_ascii=False, indent=2))

                self.send_response(200)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.end_headers()
                response = {"status": "success", "message": "JSON received"}
                self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))

            # 处理multipart/form-data (同时包含JSON和PDF)
            elif 'multipart/form-data' in content_type:
                content_length = int(self.headers.get('Content-Length', 0))
                content = self.rfile.read(content_length)

                boundary = self.headers['Content-Type'].split('boundary=')[1]
                parts = self.parse_multipart(content, boundary)

                json_data = {}
                pdf_info = None

                # 处理各个部分
                for field_name, field_data in parts.items():
                    if field_name == 'param' and not field_data['is_file']:
                        try:
                            json_data = json.loads(field_data['value'])
                            print("\nReceived JSON data in multipart:")
                            print(json.dumps(json_data, ensure_ascii=False, indent=2))
                            # 打印userName
                            print(json_data["patient_name"])
                            self.json_obj["userName"] = json_data["patient_name"]
                        except json.JSONDecodeError as e:
                            print(f"JSON decode error: {e}")

                    elif field_name == 'file' and field_data['is_file']:
                        if not field_data['filename'].lower().endswith('.pdf'):
                            raise ValueError("Only PDF files are accepted")

                        filename = self.generate_timestamp_filename(field_data['filename'])
                        save_path = os.path.join(self.PDF_UPLOAD_DIR, filename)

                        # 打印pdf的path
                        dir_path = os.path.dirname(os.path.abspath(__file__))
                        print(dir_path+"\\"+f"{self.PDF_UPLOAD_DIR}"+"\\"+f"{filename}")
                        self.json_obj["path"] = dir_path+"\\"+f"{self.PDF_UPLOAD_DIR}"+"\\"+f"{filename}"
                        print(json.dumps(self.json_obj, ensure_ascii=False, indent=4))
                        self.post_js_http_server()

                        with open(save_path, 'wb') as f:
                            f.write(field_data['content'])

                        print(f"\nReceived and saved PDF file: {filename}")

                        pdf_info = {
                            'filename': filename,
                            'saved_path': save_path
                        }

                # 构建响应
                response = {"status": "success"}
                if json_data:
                    response["message"] = "Data received successfully"
                    response["data"] = json_data
                if pdf_info:
                    response["message"] = "File uploaded successfully"
                    response.update(pdf_info)

                self.send_response(200)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.end_headers()
                self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))

            else:
                self.send_response(400)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.end_headers()
                response = {"status": "error", "message": "Unsupported Content-Type"}
                self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))

        except Exception as e:
            self.send_response(500)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.end_headers()
            response = {"status": "error", "message": str(e)}
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))
            print(f"\nError processing request: {e}")

    def post_js_http_server(self, json_data):
        url = 'http://localhost:3000/api/report/upload'
        # 发送 POST 请求
        response = requests.post(url, json=self.json_obj)
        # 输出响应
        print("状态码:", response.status_code)
        print("响应内容:", response.text)


def run(server_class=HTTPServer, handler_class=RequestHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f'Starting httpd server on port {port}...')
    print(f'Listening for POST requests at /elkhisagent/report/upload')
    httpd.serve_forever()

if __name__ == '__main__':
    run()
